//
//  forgotViewController.m
//  B项目
//
//  Created by lanou on 16/8/6.
//  Copyright © 2016年 Work. All rights reserved.
//

#import "forgotViewController.h"
#import "PrefixHeader.pch"
#import <AVOSCloud/AVOSCloud.h>
#import "YGValidator.h"
@interface forgotViewController ()<UITextFieldDelegate>
//手机号
@property(nonatomic,strong)UITextField *userTF;

//验证码密码
@property(nonatomic,strong) UITextField *passWordUserTF;

//新密码
@property(nonatomic,strong)UITextField *NewpassWordUserTF;
//再次输入新密码
@property(nonatomic,strong)UITextField *ReNewpassWordUserTF;

//获取验证码
@property(nonatomic,strong)UIButton *button;

@end

@implementation forgotViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"找回密码";
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(leftItemAction)];
    self.navigationItem.leftBarButtonItem = leftItem;
    [self setforGet];


}

- (void)leftItemAction
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)setforGet
{
    UIView *userView = [[UIView alloc]initWithFrame:CGRectMake(20, 30, kScreenWidth - 40, 60)];

    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 45, userView.ownWidth, 1)];
    lineView.backgroundColor = [UIColor grayColor];
    UIImageView *userImg = [[UIImageView alloc]initWithFrame:CGRectMake(0,10, 30, 30)];

    userImg.image = [UIImage imageNamed:@"phone.png"];

    self.userTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 10, userView.ownWidth -40, 30)];
    _userTF.tag = 10;
    _userTF.delegate = self;
    _userTF.placeholder = @"请输入手机号";
    _userTF.font = [UIFont systemFontOfSize:14];
    [_userTF setBorderStyle:(UITextBorderStyleNone)];
    [userView addSubview:_userTF];
    [userView addSubview:userImg];
    [userView addSubview:lineView];
    [self.view addSubview:userView];



    UIView *passWordView = [[UIView alloc]initWithFrame:CGRectMake(20, 90, kScreenWidth - 40, 60)];
    passWordView.userInteractionEnabled = YES;

    UIView *lineViewP = [[UIView alloc]initWithFrame:CGRectMake(0, 45, userView.ownWidth, 1)];
    lineViewP.backgroundColor = [UIColor grayColor];
    UIImageView *passWordImg = [[UIImageView alloc]initWithFrame:CGRectMake(0,10, 30, 30)];
    passWordImg.image = [UIImage imageNamed:@"yanzheng.png"];

    self.passWordUserTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 10, passWordView.ownWidth -120, 30)];
    _passWordUserTF.tag = 11;
    _passWordUserTF.delegate = self;
    _passWordUserTF.placeholder = @"请输入验证码";
    _passWordUserTF.font = [UIFont systemFontOfSize:14];
    [_passWordUserTF setBorderStyle:(UITextBorderStyleNone)];

    self.button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _button.frame = CGRectMake(passWordImg.ownWidth + _passWordUserTF.ownWidth, 10, 100, 30);
    [_button setTitle:@"获取验证码" forState:(UIControlStateNormal)];
    _button.titleLabel.font = [UIFont systemFontOfSize:12];

    [_button setTitleColor:[UIColor blueColor] forState:(UIControlStateNormal)];
    [_button addTarget:self action:@selector(btAction) forControlEvents:(UIControlEventTouchUpInside)];

    [passWordView addSubview:lineViewP];
    [passWordView addSubview:_passWordUserTF];
    [passWordView addSubview:passWordImg];
    [passWordView addSubview:_button];
    [self.view addSubview:passWordView];

    //新密码
    UIView *newPassView = [[UIView alloc]initWithFrame:CGRectMake(20, 150, kScreenWidth - 40, 60)];
    UIImageView *newImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 10, 30, 30)];
    newImg.image = [UIImage imageNamed:@"password.png"];

    self.NewpassWordUserTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 10, newPassView.ownWidth -120, 30)];
    _NewpassWordUserTF.tag = 12;
    _NewpassWordUserTF.delegate = self;
    _NewpassWordUserTF.placeholder = @"请输入新密码";
    _NewpassWordUserTF.font = [UIFont systemFontOfSize:14];
    [_NewpassWordUserTF setBorderStyle:(UITextBorderStyleNone)];

    UIView *newlineViewP = [[UIView alloc]initWithFrame:CGRectMake(0, 45, newPassView.ownWidth, 1)];
    newlineViewP.backgroundColor = [UIColor grayColor];

    [newPassView addSubview:newImg];
    [newPassView addSubview:_NewpassWordUserTF];
    [newPassView addSubview:newlineViewP];
    [self.view addSubview:newPassView];

    //再次输入新密码
    UIView *ReNewPassView = [[UIView alloc]initWithFrame:CGRectMake(20, 210, kScreenWidth - 40, 60)];
    UIImageView *ReNewImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 10, 30, 30)];
    ReNewImg.image = [UIImage imageNamed:@"password.png"];

    self.ReNewpassWordUserTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 10, ReNewPassView.ownWidth -120, 30)];
    self.ReNewpassWordUserTF.placeholder = @"请输入新密码";
    _ReNewpassWordUserTF.tag = 13;
    _ReNewpassWordUserTF.delegate = self;
    self.ReNewpassWordUserTF.font = [UIFont systemFontOfSize:14];
    [self.ReNewpassWordUserTF setBorderStyle:(UITextBorderStyleNone)];

    UIView *RenewlineViewP = [[UIView alloc]initWithFrame:CGRectMake(0, 45, ReNewPassView.ownWidth, 1)];
    RenewlineViewP.backgroundColor = [UIColor grayColor];

    [ReNewPassView addSubview:ReNewImg];
    [ReNewPassView addSubview:self.ReNewpassWordUserTF];
    [ReNewPassView addSubview:RenewlineViewP];
    [self.view addSubview:ReNewPassView];


    //完成

    UIImageView *completeImg = [[UIImageView alloc]initWithFrame:CGRectMake(20, 300, kScreenWidth - 40, 30)];
    completeImg.userInteractionEnabled = YES;
    completeImg.image = [UIImage imageNamed:@"login_tip_button@2x.png"];
    UIButton *completeBT = [[UIButton alloc]initWithFrame:CGRectMake((completeImg.ownWidth -60)/2, 0, 60, 30)];
    [completeBT setTitle:@"完成" forState:(UIControlStateNormal)];
    [completeBT setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [completeBT addTarget:self action:@selector(loaginBTAction) forControlEvents:(UIControlEventTouchUpInside)];
    [completeImg addSubview:completeBT];
    [self.view addSubview:completeImg];

}


//获取验证码点击事件
- (void)btAction
{

    if ([_userTF.text isEqualToString:@""]) {
        [self showAlert:@"手机号码不能为空"];
    }else{

        if (_userTF.text.length != 11) {
            [self showAlert:@"手机号码格式不正确"];
        }else{

            __block int timeout=60; //倒计时时间

            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

            dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行

            dispatch_source_set_event_handler(_timer, ^{

                if(timeout<=0){ //倒计时结束，关闭

                    dispatch_source_cancel(_timer);

                    dispatch_async(dispatch_get_main_queue(), ^{

                        //设置界面的按钮显示 根据自己需求设置

                        [_button setTitle:@"重新获取" forState:UIControlStateNormal];

                        _button.userInteractionEnabled = YES;
                        [_button setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];

                    });

                }else{

                    int seconds = timeout;

                    NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];

                    dispatch_async(dispatch_get_main_queue(), ^{

                        [_button setTitleColor:[UIColor greenColor] forState:(UIControlStateNormal)];
                        _button.userInteractionEnabled = NO;

                        //设置界面的按钮显示 根据自己需求设置

                        [UIView beginAnimations:nil context:nil];

                        [UIView setAnimationDuration:1];

                        [_button setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];

                        [UIView commitAnimations];

                    });

                    timeout--;

                }

            });

            dispatch_resume(_timer);

            //获取验证码
            [AVUser requestPasswordResetWithPhoneNumber:_userTF.text block:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    [self showAlert:@"验证码发送成功"];
                }else{
                    [self showAlert:@"验证码发送失败"];
                    NSLog(@"发送失败");
                    NSLog(@"%@",error);
                }
                // 发送失败可以查看 error 里面提供的信息
            }];
        }




    }
}

//点击完成按钮
- (void)loaginBTAction
{
    if ([_userTF.text isEqualToString:@""]||[_passWordUserTF.text isEqualToString:@""]||[_NewpassWordUserTF.text isEqualToString:@""]||[_ReNewpassWordUserTF.text isEqualToString:@""]) {
        [self showAlert:@"请补全信息"];
    }else{
        if ([_NewpassWordUserTF.text isEqualToString:_ReNewpassWordUserTF.text]) {

            [AVUser resetPasswordWithSmsCode:_passWordUserTF.text newPassword:self.NewpassWordUserTF.text block:^(BOOL succeeded, NSError *error) {

                if (succeeded) {
                    UIAlertController *alerC = [UIAlertController alertControllerWithTitle:@"恭喜，成功找回密码" message:@"是否返回登陆页面，重新登陆" preferredStyle:(UIAlertControllerStyleAlert)];
                    UIAlertAction *alerActionTrue = [UIAlertAction actionWithTitle:@"是" style:(UIAlertActionStyleDefault) handler:nil];
                    UIAlertAction *alerActionFalse = [UIAlertAction actionWithTitle:@"否" style:(UIAlertActionStyleDefault) handler:nil];
                    [self presentViewController:alerC animated:YES completion:nil];
                    [alerC addAction:alerActionTrue];
                    [alerC addAction:alerActionFalse];

                } else {
                    [self showAlert:@"发生错误"];

                }

            }];

        }else{
            [self showAlert:@"请核对密码后重新输入"];
        }
    }
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

    NSMutableString *currentPassWordStr = [NSMutableString stringWithString:_userTF.text];
    [currentPassWordStr replaceCharactersInRange:range withString:string];
    [YGValidator validateText:currentPassWordStr regular:@"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$" textField:_userTF correctImage:@"true" errorImage:@"error"];
    return YES;
}

//回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSInteger tag = textField.tag;
    if (tag != 13) {
        [[self.view viewWithTag:tag + 1]becomeFirstResponder];
    }else
    {
        [[self.view viewWithTag:tag]resignFirstResponder];
    }

    return YES;
}



//点击事件的提示框
- (void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
}


- (void)showAlert:(NSString *) _message{//时间
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:1.5f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:YES];
    [promptAlert show];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
